package com.nuanshui.heatedloan.socket.msg;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.socket.ProtoMsg;

/**
 * 数据传输编码和解码
 * @author GH
 *
 */
public class ProtoMsgCodec extends ByteToMessageCodec<ProtoMsg.Msg.Builder> {
	private static final Logger logger = LoggerFactory.getLogger(ProtoMsgCodec.class);
	private ByteBuffer bf = ByteBuffer.allocate(1024);//初始化大小
	
	
	/**
	 * 消息接受解码
	 */
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf buffer,
			List<Object> out) throws Exception {
		logger.info("开始解码：");
		try {
			while (buffer.readableBytes() > 0) {
				byte b = buffer.readByte();
				bf.put(b);
			}		
			byte[] bytes = new byte[bf.position()];
			bf.position(0);
			bf.get(bytes);
			bf.clear();
			out.add(bytes);
		} catch (Exception e) {
			logger.error("解码异常:"+e.toString());
		}
	}
	
	
	/**
	 * 消息发送编码
	 */
	@Override
	protected void encode(ChannelHandlerContext ctx, ProtoMsg.Msg.Builder build, ByteBuf out)
			throws Exception {
	
		ProtoMsg.Msg  msg =     build.build();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		msg.writeTo(output);		
		// -------------- 分割线：上面是发送方，将数据序列化后发送 ---------------		
		byte[] byteArray = output.toByteArray();	
		LogUtil.info(logger, "发送消息了：+++++++++++++++++");
		out.writeBytes(byteArray);
	}
}
